package org.lim.shared.websocket.service.strategy;

import org.lim.shared.websocket.model.enums.PictureEditMessageTypeEnum;
import org.lim.shared.websocket.service.PictureEditBroadcastService;
import org.lim.shared.websocket.service.PictureEditStateService;
import org.lim.shared.websocket.model.PictureEditRequestMessage;
import org.lim.shared.websocket.model.PictureEditResponseMessage;
import org.lim.domain.user.entity.User;
import org.lim.application.service.UserApplicationService;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

@Component("exitEditStrategy")
public class ExitEditStrategy implements PictureEditMessageStrategy {
    
    @Resource
    private UserApplicationService userApplicationService;
    
    @Resource
    private PictureEditBroadcastService broadcastService;
    
    @Resource
    private PictureEditStateService stateService;
    
    @Override
    public void handleMessage(PictureEditRequestMessage requestMessage, WebSocketSession session, User user, Long pictureId) throws Exception {
        Long editingUserId = stateService.getEditingUserId(pictureId);
        
        if (editingUserId != null && editingUserId.equals(user.getId())) {
            // 移除当前用户的编辑状态
            stateService.removeEditingUser(pictureId);
            
            // 构造响应，发送退出编辑的消息通知
            PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
            responseMessage.setType(PictureEditMessageTypeEnum.EXIT_EDIT.getValue());
            String message = String.format("%s退出编辑图片", user.getUserName());
            responseMessage.setMessage(message);
            responseMessage.setUser(userApplicationService.getUserVO(user));
            
            broadcastService.broadcastToPicture(pictureId, responseMessage);
        }
    }
}